<?php
// +----------------------------------------------------------------------
// | najing [ 通用后台管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.najingquan.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 救火队队长
// +----------------------------------------------------------------------

namespace  app\index\controller;

use app\api\controller\PublicApi;
use app\common\controller\IndexController;

use app\index\model\FundCard;
use app\index\model\FundCheck;
use app\index\model\UserIp;
use app\index\model\UserLog;
use app\index\model\UserToken;
use think\App;
use think\facade\Db;
use think\facade\Log;
use think\facade\Request;
use think\facade\View;
use think\facade\Cache;
use app\api\controller\EmailSend;

/**
 * 会员管理
 * Class User
 * @package app\admin\controller
 */
class User extends  IndexController
{
    private $apiKey = 'fTMPeNXomn7';
    private $apiSecret = 'W5aC0w6Geg2AxmU5bQYS';

    public function __construct(App $app)
    {
        parent::__construct($app);
        View::assign([
            'menu_class' => 'user',
        ]);
    }

    public function account()
    {
        $user_list = Db::name('user')->find($this->user_id);
        $cardSetList        = $this->getCardSet();
        $card_max           = $cardSetList['max_card']; //建卡上限
        View::layout(true);
        View::assign([
            'menu_child'    => 'user_account',
            'list'          => $user_list,
            'card_max'      => $card_max,
            'grade'         => $user_list['grade'],
            'name'          => userNameCut($user_list['name']),
            'id_card'       => !empty($user_list['id_card'])?substr($user_list['id_card'],0,6) . '******': '---',
        ]);
        return View::fetch();
    }

    public function fundList()
    {
        $fcModel = new FundCheck();
        return $fcModel->tableData(input('param.') + ['user_id' => $this->user_id]);
    }

    public function userLog()
    {
        $fcModel = new UserToken();
        return $fcModel->tableData(input('param.') + ['user_id' => $this->user_id]);
    }

    /**
        * 支付宝人脸验证
     */
    public function cardCheck()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            $user_name = trim($data['user_name']);
            $card_num = trim($data['card_num']);
            $captcha  = trim($data['captcha']);
            if (!captcha_check($captcha)) {
                return $this->err('验证码错误.');
            }
            $check_list = Db::name('user')->where("id_card='{$card_num}'")->find();
            if(!empty($check_list)){
                return $this->err('身份证号码重复.');
            }
            if (!check_param($card_num, 'user_card')) return $this->err('身份证格式错误.');
            $param = Cache::store('redis')->get('card_check_' . $this->user_id);
            if(!empty($param)){
                return $this->err('认证正在进行中，请勿重复提交，或者1分钟后再提交.');
            }

            //2024-9-22 暂停人脸认证
//            $re = Db::name('user')->where(['id'=>$this->user_id])
//                ->update([
//                    'grade'     => 1,
//                    'name'      => $user_name,
//                    'id_card'   => $card_num
//                ]);
//            if($re){
//                return $this->scs('认证成功.' ,'user/account');
//            }else{
//                return $this->err('认证失败.');
//            }

//            $account = array(
//                "appid"      => "2021004124669625",
//                "privateKey" => "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDSEAIQOtzM4H3cA75GaqzIy6Llrtd4Mad4eN54xRNFxOr5MDdSWqNhjDgvtcaLblmzuPL4GMxzgMAw4TRw2z/IWmGMpeMxuTmkSNNwiYPqQ6llpIwdAFpuPM0mEauGkRhZTLOD/9Ip8yc5eTefT6euy4BX3IJ//rxZXEPH5nzZ2fVE7N1wbmmwI6BJUZbLuy8hg4c0kXQHdGpHGGENzPGrlkNUhKnCZXF4nfKB8v0hLKyWLB5QsKY7pYj8xOkFPblQa3lN3D70xDt3GBCMkV9+mYhqXfsABhifKLeaO1dkeaOF1QEkaqGUptHt2H+rybOnA1aab/0tqUY1w5E6ami/AgMBAAECggEASrorIb7u4WtTGruyKra0NNJMZszmFfoEC5Vj/y6Mhptgw7jlVUStLnyFWGOf9+YPvyGiPaQEx2ob9MeIskUs0YdlgHVa90tfOBQ4M6aX6PSdBG2e8oo3oVO73zkV/c8MDGh+zAxrpUS8xXNb2C6sBkCarabiPcpPErMB4dEaxRxhYHiGDsOFKbWftK2W7iQsZ0Ewrz5B7i79MYkjmOGXTx/iNeER7IEBZULaQTRsTHq16YKjyzFA6mTryoIsUPVxfbMAHLTpQAkEy3goLvT3ZPvoX70vp0bLPghk41ie6bUj814FDODUgaLt0DFE994C1uq+8urRwf/hp74gzFaPwQKBgQDsfI4747/+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2/SWHWvEnMlWdQLi9s6jaT/UF9t/6GFVj37bRKjxd0NHHODxco/fxv4GOON65kFV1WtPMTBaVX8j/GedIUcl/VukBW662UrqqEiiYgP1+wPuzbbUHTNcnFQVUt3sx4D2sRfryltb/DOeP5q6NXZbofrEdZpoG0fRpvj5Cyc2NuwwPBOLDPV73fSrmlRREEakpH1PKLQIDAQAB"
//            );
            $account = self::getAppKey();

            $result = self::testRz($account , $user_name ,$card_num , $this->user_id);
            $blog   = $result['blog'] ?? false;
            if($blog){
                return $this->scs('获取二维码成功','',$result['msg']);
            }else{
                $username = session('user.username');
                EmailSend::sendEmail('user_idCard_check' , [
                    'email'     => getSetting('fund_email_send'),
                    'desc'      => "【人脸识别出错】, 错误原因:" . $result['msg'] ." , 客户邮箱: {$username} "
                ]);
                return $this->err($result['msg']);
            }
        }
        $grade_new = Db::name('user')->where(['id'=>$this->user_id])->value('grade_new');
        if($grade_new == 2){
            $this->redirect(url('user/idCheck'));
        }
        Cache::store('redis')->delete('card_check_' . $this->user_id);

        View::assign([
            'menu_child'    => 'card_check',
        ]);
        return View::fetch();
    }

    public static function testRz($account , $user_name , $card_num , $user_id)
    {
        $aop = new \aop\AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $account['appid'];
        $aop->rsaPrivateKey = $account['privateKey'];
        $aop->alipayrsaPublicKey=$account['publicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \aop\request\AlipayUserCertifyOpenInitializeRequest();
        $outer_order_no = 'test' . getUtcTime();
        $request->setBizContent("{" .
            "  \"outer_order_no\":\" " . $outer_order_no . " \"," .
            "  \"biz_code\":\"FACE\"," .
            "  \"identity_param\":{" .
            "    \"identity_type\":\"CERT_INFO\"," .
            "    \"cert_type\":\"IDENTITY_CARD\"," .
            "    \"cert_name\":\" " . $user_name . " \"," .
            "    \"cert_no\":\" " . $card_num . " \"" .
            "  }," .
            "  \"merchant_config\":{" .
            "    \"face_reserve_strategy\":\"reserve\"," .
            "    \"return_url\":\"\"" .
            "  }" .
            "}");
        $result = $aop->execute ($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $result = $result->$responseNode;
        $resultCode = $result->code;

        if(!empty($resultCode)&&$resultCode == 10000){
            $certify_id = $result->certify_id;
           // var_dump($certify_id);
            Cache::store('redis')->set('card_check_' . $user_id , [
                'certify_id' => $certify_id,
                'user_name'  => $user_name,
                'card_num'   => $card_num
            ],120);
            Db::name("user_face")->save([
                'user_id'       => $user_id,
                'certify_id'    => $certify_id,
                'user_name'     => $user_name,
                'id_card'       => $card_num,
                'ctime'         => getUtcTime()
            ]);
            return [
                'blog' => true,
                'msg' => self::testRz2($account , $certify_id)
            ];
        } else {
            self::alipayErrorLog($user_id,'alipay_open_initialize',$resultCode);
            return [
                'blog' => false,
                'msg' => self::alipayErrorMsg($resultCode)
            ];
        }
    }

    public static function alipayErrorMsg($resultCode)
    {
        $error_msg = [
            20000 => '服务不可用',
            20001 => '授权权限不足',
            40001 => '缺少必选参数',
            40002 => '非法的参数',
            40003 => 'Insufficient Conditions(条件异常)',
            40004 => '业务处理失败',
            40005 => 'Call Limited(调用频次超限)',
            40006 => '权限不足'
        ];
        return $error_msg[$resultCode] ?? '获取二维码失败,请联系管理员';
    }

    public static function alipayErrorLog($user_id,$type,$resultCode)
    {
        $resultCode = empty($resultCode)?'':$resultCode;
        $ctime      = getUtcTime();

        $error_list = Db::name('alipay_error')->where([
            'user_id'   => $user_id,
            'type'      => $type,
            'data_param'=> $resultCode,
            'desc'      => self::alipayErrorMsg($resultCode)
        ])->find();
        if($error_list){
            Db::name('alipay_error')->where([
                'user_id'   => $user_id,
                'type'      => $type,
                'data_param'=> $resultCode
            ])->update(['ctime' => $ctime]);
        }else{
            Db::name('alipay_error')->save([
                'user_id'   => $user_id,
                'type'      => $type,
                'data_param'=> $resultCode,
                'desc'      => self::alipayErrorMsg($resultCode),
                'ctime'     => getUtcTime()
            ]);
        }
    }
    public static function testRz2($account , $certify_id)
    {
        $aop = new \aop\AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = $account['appid'];
        $aop->rsaPrivateKey = $account['privateKey'];
        $aop->alipayrsaPublicKey=$account['publicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \aop\request\AlipayUserCertifyOpenCertifyRequest ();
        $request->setBizContent("{" .
            "  \"certify_id\":\"" . trim($certify_id)."\"" .
            "}");
        return $aop->pageExecute ( $request ,'get' );
//        return "https://api.qrserver.com/v1/create-qr-code/?size=150%C3%97150&data=" . $result;
//        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $resultCode = $result->$responseNode->code;
//        if(!empty($resultCode)&&$resultCode == 10000){
//            echo "成功";
//        } else {
//            echo "失败";
//        }
    }
    private static function getAppKey()
    {
        //2025-03-05更新  cardecho
        return array(
            "appid"      => "2021005123691870",
            "privateKey" => "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCMFMO8g6hDl8dPUE6bDI8J6zbwA7tJP/4qPuiUGyYCm7plLpliQuoSjr7UjP9zkrbpoFrHUjR43rj5TFSVPrd/SZvEx4O/cPFKAt+iLvI6nskYBoNMqiW0HqWketBghi9YlQZRpncV0cjCGvngyZmKmI9SBdedGqys2gyl73oprPhne8R3L4mVvVklxkpnEg0t6rdo2eEnNvlblTGWfMn0QAS3EAXDAHYAZxV9S3hWCfsTjvoGU5nqc/lU1zXposZ8bY7NB4hcfCQV34Ayk9rqd3Lt43Um3u4muImL48aIafldVTxp9X073dyea3pPPYLVeE0bcHtkmMJbFOFMFlfXAgMBAAECggEAaZziMohE3alaYMcYbLfcREst4Wm+06xGsY06hyes0bydnNm0VSxEFHfBErm3g2hzNdNrfenRm+u4JGVTRC7D5FkX8xXFlBnQIc/m0f15LY836EBI0A1cXd/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k9bSyKSdHWlOQ==",
            "publicKey"  => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlcV+SVQmCiDyvwLloZbxZ4PJ4ozht29VvOhcQkg6geGzNZK//azlDSnZAvE6CAFWAJULyqW38jl6Itgb39Bn/votO/fibj6sYa2hSHHGxDya0Oqb6uWY+LuKDie8UygoIr5JObwFEwGzOqcYq5KVE2OfU0PemFeSCSB8m9MqdQC5nEh7uPWjynwRx5KwSW183vHUuFUQxlDYXOmAzoIPJ7ooj30285Qm9Pms8zLKiwRrtOoCksemYxbzxUAkE7rYCFG60D6dkrYRfS/tcIuOdmCxkTy7Mq+k7dZ0ZsyfYXwNoKm21slodCsEGd8/hAYeWOsHAZ6YDHp/i6f4nksmmQIDAQAB"
        );
    }

    public function rzCheck()
    {
        $account = self::getAppKey();

        $param = Cache::store('redis')->get('card_check_' . $this->user_id);
        if(!empty($param)){
            $certify_id = $param['certify_id'];
            $user_name  = $param['user_name'];
            $card_num   = $param['card_num'];

            $aop = new \aop\AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $account['appid'];
            $aop->rsaPrivateKey = $account['privateKey'];
            $aop->alipayrsaPublicKey=$account['publicKey'];
            $aop->apiVersion = '1.0';
            $aop->signType = 'RSA2';
            $aop->postCharset='UTF-8';
            $aop->format='json';
            $request = new \aop\request\AlipayUserCertifyOpenQueryRequest ();
            $request->setBizContent("{" .
                "'certify_id':'" . $certify_id . "'" .
                "}");
            $result = $aop->execute ( $request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $result     = $result->$responseNode;
            $resultCode = $result->code;
//            dd($result);
            $time = getUtcTime();
            if(!empty($resultCode)&&$resultCode == 10000){
                $passed = $result->passed;
                if($passed == "T"){
                    $user_face_list = Db::name("user_face")->where(['certify_id'    => $certify_id])->find();
                    if(!empty($user_face_list)){
                        Db::name("user_face")->where(['certify_id'    => $certify_id])
                            ->update([
                                'utime' => $time,
                                'is_ok' => 1,
                            ]);
                    }else{
                        Db::name("user_face")->save([
                            'user_id'       => $this->user_id,
                            'certify_id'    => $certify_id,
                            'user_name'     => $user_name,
                            'id_card'       => $card_num,
                            'is_ok'         => 1,
                            'utime'         => $time,
                        ]);
                    }
                    $re = Db::name('user')->where(['id'=>$this->user_id])
                        ->update([
                            'grade'     => 1,
                            'grade_new' => 1,
                            'name'      => $user_name,
                            'id_card'   => $card_num
                        ]);
                    if($re){
                        return true;
                    }else{
                        return false;
                    }
                }
            } else {
                self::alipayErrorLog($this->user_id,'alipay_open_query',$resultCode);
                return false;
            }
        }else{
            return false;
        }
    }
    public function rzSend()
    {
        $data       = input('param.');
        if(empty($data['rz_name'])) return $this->err('姓名不能为空.');
        if(empty($data['rz_card'])) return $this->err('身份证不能为空.');
        if(!check_param($data['rz_card'],'user_card')) return $this->err('身份证格式错误.');
        $grade      = Db::name('user')->where(['id' => $this->user_id])->value('grade');
        if($grade == 1) return $this->err('用户已认证.');
        $result     = PublicApi::rzSend($data['rz_name'] , $data['rz_card']);
        $code       = $result['code'] ?? '';
        $response   = $result['response'] ?? '';
        $blog       = false;
        if(!empty($code) && substr($code , 0 , 1) == 2){
            $response = json_decode($response , true);
            $re_code  = $response['code'];
            if($re_code == 0){
                $blog = true;
            }
        }
        if($blog){
            Db::name('user')->where(['id' => $this->user_id])->update([
                'grade'     => 1, //0=普通用户，1=认证用户
                'name'      => $data['rz_name'],
                'id_card'   => $data['rz_card'],
            ]);
            return $this->scs('认证成功.');
        }else{
            return $this->err('认证失败.');
        }
    }

    public function changePwd()
    {
        $data               = input('param.');
        $old_pwd            = $data['old_pwd'];
        $change_pwd         = $data['change_pwd'];
        $change_pwd_confirm = $data['change_pwd_confirm'];

        if(empty($old_pwd)) return $this->err('旧密码不能为空.');
        if(empty($change_pwd)) return $this->err('修改密码不能为空.');
        if(empty($change_pwd_confirm)) return $this->err('确认密码不能为空.');
        if(!check_param($change_pwd , 'password')) return json(['code'=>0,'msg'=>"密码必须为(大小写字母,数字和特殊字符组合12-36)."]);

        $user_list  = Db::name('user')->where(['id'=>$this->user_id])->find();
        if(!$user_list) return $this->err('旧密码错误.');
        $ctime      = $user_list['ctime'];
        $pwd        = $user_list['password'];
        if(md5(md5($old_pwd) . $ctime) != $pwd){
            return $this->err('旧密码错误.');
        }
        $re         = Db::name('user')->where(['id'=>$this->user_id])
                        ->update(['password'=> md5(md5($change_pwd) . $ctime)]);
        if($re){
            return $this->scs('修改密码成功.');
        }else{
            return $this->err('修改密码失败.');
        }
    }

    public function changePay()
    {
        $data               = input('param.');
        $alipay_name        = trim($data['alipay_name'] ?? '');
        $we_chat            = trim($data['we_chat'] ?? '');
        $captcha            = trim($data['captcha']);
        if (!captcha_check($captcha)) {
            return $this->err('验证码错误.');
        }

        $user_list  = Db::name('user')->where(['id'=>$this->user_id])->find();
        $alipay_name_db = $user_list['alipay_name'];
        $we_chat_db     = $user_list['we_chat'];

        $where      = [];
        if($alipay_name_db == '***'){
            if(empty($alipay_name)) return $this->err('支付宝账号不能为空.');
            $where['alipay_name'] = $alipay_name;
        }
        if($we_chat_db == '***'){
            if(empty($we_chat)) return $this->err('微信账号不能为空.');
            $where['we_chat'] = $we_chat;
        }

        $re  = Db::name('user')->where(['id'=>$this->user_id])
            ->update($where);
        if($re){
            return $this->scs('绑定成功.');
        }else{
            return $this->err('绑定失败.');
        }
    }

    public function userDetail()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            $user_name = trim($data['user_name']);
            $card_num = trim($data['card_num']);
            $captcha  = trim($data['captcha']);
            if (!captcha_check($captcha)) {
                return $this->err('验证码错误.');
            }
            $check_list = Db::name('user')->where("id_card='{$card_num}'")->find();
            if(!empty($check_list)){
                return $this->err('身份证号码重复.');
            }
            if (!check_param($card_num, 'user_card')) return $this->err('身份证格式错误.');
            $param = Cache::store('redis')->get('card_check_' . $this->user_id);
            if(!empty($param)){
                return $this->err('认证正在进行中，请勿重复提交，或者1分钟后再提交.');
            }
            $account = array(
                "app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e1dd2FoBTgteQG87MeKNtFOl/lBsJaSWrIDloExzwKBgQCFLFdErqqtxyl6XWf/OQrNQx8+pnp2OQNnHaILDdNnsY4hE3KsGioHpTR9vqZooA9BlrASUpcnmPEpiyrX7zRui3ThuuC4ntbPfUKs96dCSS31/J7Vj5ZeZZzyefat+U/PSkFHR8uWtyrWLqu1EBA+H3W6aTS6hWQu2xrcI8h+oQKBgQDALKZyV2MnhlF/dtuQbvtzuM3XwHCvPzv6HmEm1QjTDlC7zjQEqI2UnJZHQfT4PkjbqhAWdi7jn9rFiNaRHRbxrUXn8t2Y1Dh37abdKbzVR0BSJot6m+CyavX1Ym/7wGIl561MokmFuXOCqpNXcNwp6K33N+SFKZH22gM7mQRSbQKBgFRRn8cUTNVmDe99Gahweg5L3a9ThsPO3y/VnGQlesKvGWdy6Qg+0HJtfsLu7wjaBa3ZWIDt+4HKPC0TuDoByH0sw4dYP2Bg8FHJJi7UnAGqzZl/AyTfSxezxos8acab0m0Y+Fi338m5qeb4Ytewj9M2qO9yDCXMVmZ1OZWfMaXm",
                "publicKey"  => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoBGYCBjCb6NT19oFtRxJ8PHdpqqDsaybYYoQJdnDYWTWWpQquOSRp09JjfIZo8RDHe5NkGQvoOTjnOpqJC0nsdRwBPsbgL4ia551H8CwQg9AkyfBjHa+DpP4ighCZrTfWzjPHL79g0Bor+v2/SWHWvEnMlWdQLi9s6jaT/UF9t/6GFVj37bRKjxd0NHHODxco/fxv4GOON65kFV1WtPMTBaVX8j/GedIUcl/VukBW662UrqqEiiYgP1+wPuzbbUHTNcnFQVUt3sx4D2sRfryltb/DOeP5q6NXZbofrEdZpoG0fRpvj5Cyc2NuwwPBOLDPV73fSrmlRREEakpH1PKLQIDAQAB"
            );

            $result = self::testRz($account , $user_name ,$card_num , $this->user_id);
            $blog   = $result['blog'] ?? false;
            if($blog){
                return $this->scs('获取二维码成功','',$result['msg']);
            }else{
                $username = session('user.username');
                $result = EmailSend::sendGridEmail('user_idCard_check' , [
                    'email'     => getSetting('fund_email_send'),
                    'title'     => 'cardecho 支付宝人脸识别错误',
                    'body'      => "【人脸识别出错】, 错误原因:" . $result['msg'] ." , 客户邮箱: {$username} "
                ]);
                return $this->err($result['msg']);
            }
        }
//        $grade_new = Db::name('user')->where(['id'=>$this->user_id])->value('grade_new');
//        if($grade_new == 1){
//            $this->redirect(url('user/account'));
//        }
        $user_list = Db::name('user')->find($this->user_id);

        View::assign([
            'menu_child'    => 'card_check',
            'list'          => $user_list,
        ]);
        return View::fetch();
    }

    /**
     * veriff 验证
     */
    public function idCheck()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            $first_name = trim($data['first_name']);
            $last_name  = trim($data['last_name']);
            $user_card =  trim($data['user_card']);
            $captcha  = trim($data['captcha']);
            $create_time = getUtcTime();
            if (!captcha_check($captcha)) {
                return $this->err('验证码错误.');
            }
            if (empty($user_card)) {
                return $this->err('身份证号码不能为空.');
            }
            $check_list = Db::name('user')
                ->where("id_card='{$user_card}'")->find();
            if (!empty($check_list)) {
                return $this->err('身份证号码已存在.');
            }
//            $count = Db::name('user_veriff')
//                ->where("user_id='{$this->user_id}'")->count();
//            if ($count>5) {
//                return $this->err('认证次数不能超过5次.');
//            }
//            $create_time = getUtcTime();
//            $check_list = Db::name('user_veriff')
//                ->where("user_id='{$this->user_id}' and is_rep is NULL")->find();
//            if(!empty($check_list)){
//                $old_time = $check_list['time'];
//                $old_id   = $check_list['id'];
//                if($create_time - $old_time >= 24*7*60*60){
//                    Db::name('user_veriff')->where('id='.$old_id)
//                        ->update(['is_rep'=>'Sys Expired']);
//                }else{
//                    return $this->err('您有正在审核的信息,请勿重复提交.');
//                }
//            }
            $param = Cache::store('redis')->get('id_check_' . $this->user_id);
            if(!empty($param)){
                return $this->err('认证信息正在提交中，请勿重复提交.');
            }
            $apiKey    = $this->apiKey;
            $apiSecret = $this->apiSecret;

            $url = "https://ivs.idenfy.com/api/v2/token";

// 先试试不传 clientId，看看返回什么
            $payload = [
                "clientId" => (string)$this->user_id,
            ];
// 或者：$payload = ["clientId" => "你在idenfy后台的clientId"];

            $auth = base64_encode($apiKey . ":" . $apiSecret);

            $ch = curl_init($url);

            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST           => true,
                CURLOPT_POSTFIELDS     => json_encode($payload),
                CURLOPT_HTTPHEADER     => [
                    "Content-Type: application/json",
                    "Authorization: Basic " . $auth,
                ],
            ]);

            $response = curl_exec($ch);

            if (curl_errno($ch)) {
                dump('cURL Error: ' . curl_error($ch));
            }

//            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

            curl_close($ch);

//            dump('HTTP Code: ' . $httpCode);
//            dump('Raw Response: ' . $response);
            $data = json_decode($response, true);

            // 正常情况下会有 authToken 和 scanRef
            $authToken = $data['authToken'] ?? null;
            $scanRef   = $data['scanRef'] ?? null;
            $url = 'https://ui.idenfy.com/?authToken=' . urlencode($authToken);

            Db::name('user_veriff')->save([
                'user_id'   => $this->user_id,
                'name'      => $first_name . ' ' . $last_name,
                'session_id'=> $scanRef,
                'time'      => $create_time,
                'url'       => $url
            ]);
//            $username = Db::name('user')->where(['id'=>$this->user_id])->value('username');
//
//            EmailSend::sendGridEmail('user_veriff_check' , [
////                'email'     => '897194@gmail.com',
//                'email'     => '455070284@qq.com',
////                'email'     => getSetting('fund_email_send'),
//                'title'     => 'cardecho veriff check',
//                'body'      => "验证用户 {$username} , session_id : {$session_id}"
//            ]);

            return $this->scs('获取二维码成功','',['session_id' => $scanRef,'url'=>$url]);
        }
        Cache::store('redis')->delete('id_check_' . $this->user_id);

//        $check_list = Db::name('user_veriff')
//            ->where("user_id='{$this->user_id}' and is_rep is NULL")->find();
//        if($check_list){
//            $this->redirect(url('user/idCheckResult'));
//        }

        View::assign([
            'menu_child'    => 'card_check',
        ]);
        return View::fetch();
    }

    public function idList()
    {
        $where[] = ['user_id','=',$this->user_id];
        $list = Db::name('user_veriff')
            ->order('time desc')
            ->field('name,id_number,is_rep,remark,time')
            ->where($where)
            ->select()
            ->toArray();

        return [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list,
            'count' => count($list),
        ];
    }

    public function idCheckVef()
    {
        $s_id = input('get.s_id');
        $blog = false;
        if(!empty($s_id)){
            $check_list = Db::name('user_veriff')
                ->where("user_id='{$this->user_id}' and session_id='{$s_id}'")->find();
            if(!empty($check_list)){
                $is_rep = $check_list['is_rep'];
                if($is_rep == 'APPROVED' || $is_rep == 'error'){
                    $blog = true;
                }
            }
        }
        return $blog;
    }

}
